package com.tools.ad.adscene.outer;

import com.hm.ads.sdk.HmAdsSDK;
import com.hm.adsbuisiness.bean.HmAdPlace;
import com.hm.adsbuisiness.bean.HmAdUnionPlace;
import com.hm.base.android.mob.AMApplication;
import com.tools.ad.ADConstant;
import com.tools.ad.AdType;
import com.tools.ad.EntranceType;
import com.tools.ad.R;
import com.tools.ad.adscene.inner.CommonInterstitialActivityScene;
import com.tools.ad.util.AppUtils;
import com.tools.ad.util.GARecordUtils;
import com.tools.ad.util.RandomUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * desc: 应用外广告 管理
 * date: 2018/4/20
 * author: ancun
 */

public class AppOuterScene extends CommonInterstitialActivityScene {

    private long lastPrepareTime;

    public AppOuterScene(AMApplication context, EntranceType entranceType) {
        super(context, entranceType);
    }

    @Override
    protected void destroyUnionPlaceAd() {
        try {
            HmAdUnionPlace unionPlace = HmAdsSDK.getInstance().getUnionAd(mCurrentPlaceId);
            if (unionPlace != null) {
                unionPlace.destory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean load(boolean forceLoad) {
        //过滤一秒内的多次触发点
        if (!repeatRequestForActivity && System.currentTimeMillis() - lastPrepareTime < 1000) {
            return true;
        }
        lastPrepareTime = System.currentTimeMillis();

        HmAdUnionPlace adUnionPlace = getRandomPlace(mEntranceType.getPidArray());
        if (adUnionPlace == null) {
            return false;
        }

        mHmAdPlace = adUnionPlace;
        mCurrentPlaceId = (int) adUnionPlace.getId();
        mExecutor = getADModule().getADStrategyManager().getExecutorByEntranceType(mEntranceType);
        if (forceLoad || mExecutor.check(adUnionPlace)) {
            return loadUnionPlace(adUnionPlace);
        }

        return false;
    }

    public boolean reload(boolean forceLoad) {
        repeatRequestForActivity = true;
        boolean result = false;

        mExecutor = getADModule().getADStrategyManager().getExecutorByEntranceType(mEntranceType);
        if (forceLoad || mExecutor.check(mHmAdPlace)) {
            result = reloadUnionPlace(mHmAdPlace);
            repeatRequestForActivity = false;
        }

        return result;
    }

    @Override
    protected void onADLoaded(AdType adType) {
        boolean inSelfApp = AppUtils.isInSelfApp();
        if (inSelfApp) {
            GARecordUtils.onADShowFailed(imContext,
                    mEntranceType.getName(),
                    adType,
                    ADConstant.ErrorCode.SELF_APP_RUNNING
            );
            return;
        }

        super.onADLoaded(adType);
    }

    @Override
    protected void onADLoad(AdType adType) {
        // 只有应用外才有广告ID的打点。
        GARecordUtils.onADLoad(imContext, mEntranceType.getName(), adType, mCurrentPlaceId);
    }

    private HmAdUnionPlace getRandomPlace(int[] pidArray) {
        //所有ad机率总和
        int total;
        //每个ad自身的机率域
        int[] scores;

        List<HmAdUnionPlace> placeIdList = new ArrayList<>();
        for (int i = 0; i < pidArray.length; i++) {
            HmAdUnionPlace unionAd = HmAdsSDK.getInstance().getUnionAd(pidArray[i]);
            if (unionAd != null) {
                placeIdList.add(unionAd);
            }
        }

        if (placeIdList.isEmpty()) {
            return null;
        }

        if (placeIdList.size() == 1) {
            return placeIdList.get(0);
        }

        int size = placeIdList.size();
        scores = new int[size];
        total = 0;
        for (int i = 0; i < size; i++) {
            HmAdPlace hmAdPlace = placeIdList.get(i);
            total += hmAdPlace.getChance();
            scores[i] = total;
        }
        return placeIdList.get(getRandomPlaceIndex(total, scores));
    }

    public int getRandomPlaceIndex(int total, int[] scores) {
        int random = RandomUtil.getRandom().nextInt(99999) % total;
        int length = scores.length;
        for (int i = 0; i < length; i++) {
            if (scores[i] > random) {
                return i;
            }
        }
        return 0;
    }

    @Override
    protected void onADLoadByActivity(AdType adType) {
        super.onADLoadByActivity(adType);
        imContext.handleMobEmptyMessage(R.id.msg_ad_need_activity);
    }
}
